<template>
  <div class="image-upload">
    <div class="upload-area" @click="triggerFileInput" @drop="handleDrop" @dragover.prevent @dragenter.prevent>
      <input
        ref="fileInput"
        type="file"
        accept="image/*"
        @change="handleFileChange"
        style="display: none"
      />
      <div v-if="!previewUrl" class="upload-placeholder">
        <i class="upload-icon">📁</i>
        <p>点击或拖拽图片到此处上传</p>
        <p class="upload-hint">支持 JPG、PNG、GIF 格式，最大 10MB</p>
      </div>
      <div v-else class="preview-container">
        <img :src="previewUrl" alt="预览" class="preview-image" />
        <div class="preview-overlay">
          <button @click.stop="removeImage" class="remove-btn">删除</button>
        </div>
      </div>
    </div>

    <div v-if="uploadProgress > 0 && uploadProgress < 100" class="progress-bar">
      <div class="progress-fill" :style="{ width: uploadProgress + '%' }"></div>
      <span class="progress-text">{{ uploadProgress }}%</span>
    </div>

    <div v-if="errorMessage" class="error-message">
      {{ errorMessage }}
    </div>

    <div v-if="successMessage" class="success-message">
      {{ successMessage }}
    </div>

    <div v-if="imageInfo" class="image-info">
      <h4>图片信息</h4>
      <p><strong>文件名:</strong> {{ imageInfo.originalFileName }}</p>
      <p><strong>大小:</strong> {{ formatFileSize(imageInfo.fileSize) }}</p>
      <p><strong>类型:</strong> {{ imageInfo.contentType }}</p>
      <p><strong>上传时间:</strong> {{ formatDate(imageInfo.createdAt) }}</p>
      <p><strong>访问地址:</strong> <a :href="imageInfo.urlPath" target="_blank">{{ imageInfo.urlPath }}</a></p>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { uploadImage } from '../api/image'

export default {
  name: 'ImageUpload',
  props: {
    description: {
      type: String,
      default: ''
    },
    tags: {
      type: String,
      default: ''
    }
  },
  emits: ['upload-success', 'upload-error'],
  setup(props, { emit }) {
    const fileInput = ref(null)
    const previewUrl = ref('')
    const uploadProgress = ref(0)
    const errorMessage = ref('')
    const successMessage = ref('')
    const imageInfo = ref(null)

    const triggerFileInput = () => {
      fileInput.value.click()
    }

    const handleFileChange = (event) => {
      const file = event.target.files[0]
      if (file) {
        validateAndPreview(file)
      }
    }

    const handleDrop = (event) => {
      event.preventDefault()
      const files = event.dataTransfer.files
      if (files.length > 0) {
        validateAndPreview(files[0])
      }
    }

    const validateAndPreview = (file) => {
      // 验证文件类型
      if (!file.type.startsWith('image/')) {
        errorMessage.value = '请选择图片文件'
        return
      }

      // 验证文件大小 (10MB)
      if (file.size > 10 * 1024 * 1024) {
        errorMessage.value = '文件大小不能超过 10MB'
        return
      }

      // 创建预览
      const reader = new FileReader()
      reader.onload = (e) => {
        previewUrl.value = e.target.result
        errorMessage.value = ''
      }
      reader.readAsDataURL(file)

      // 自动上传
      uploadFile(file)
    }

    const uploadFile = async (file) => {
      try {
        uploadProgress.value = 0
        errorMessage.value = ''
        successMessage.value = ''

        const formData = new FormData()
        formData.append('file', file)
        if (props.description) {
          formData.append('description', props.description)
        }
        if (props.tags) {
          formData.append('tags', props.tags)
        }

        // 模拟上传进度
        const progressInterval = setInterval(() => {
          if (uploadProgress.value < 90) {
            uploadProgress.value += 10
          }
        }, 100)

        const response = await uploadImage(formData)
        
        clearInterval(progressInterval)
        uploadProgress.value = 100

        if (response.success) {
          imageInfo.value = response.data
          successMessage.value = '图片上传成功！'
          emit('upload-success', response.data)
          
          // 3秒后清除成功消息
          setTimeout(() => {
            successMessage.value = ''
          }, 3000)
        } else {
          errorMessage.value = response.message || '上传失败'
          emit('upload-error', response.message)
        }
      } catch (error) {
        uploadProgress.value = 0
        errorMessage.value = '上传失败: ' + error.message
        emit('upload-error', error.message)
      }
    }

    const removeImage = () => {
      previewUrl.value = ''
      imageInfo.value = null
      errorMessage.value = ''
      successMessage.value = ''
      uploadProgress.value = 0
      if (fileInput.value) {
        fileInput.value.value = ''
      }
    }

    const formatFileSize = (bytes) => {
      if (bytes === 0) return '0 Bytes'
      const k = 1024
      const sizes = ['Bytes', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }

    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleString('zh-CN')
    }

    return {
      fileInput,
      previewUrl,
      uploadProgress,
      errorMessage,
      successMessage,
      imageInfo,
      triggerFileInput,
      handleFileChange,
      handleDrop,
      removeImage,
      formatFileSize,
      formatDate
    }
  }
}
</script>

<style scoped>
.image-upload {
  max-width: 500px;
  margin: 0 auto;
}

.upload-area {
  border: 2px dashed #ddd;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  min-height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-area:hover {
  border-color: #007bff;
  background-color: #f8f9fa;
}

.upload-placeholder {
  color: #666;
}

.upload-icon {
  font-size: 48px;
  margin-bottom: 16px;
  display: block;
}

.upload-hint {
  font-size: 12px;
  color: #999;
  margin-top: 8px;
}

.preview-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.preview-image {
  max-width: 100%;
  max-height: 300px;
  border-radius: 4px;
}

.preview-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.preview-container:hover .preview-overlay {
  opacity: 1;
}

.remove-btn {
  background: #dc3545;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.remove-btn:hover {
  background: #c82333;
}

.progress-bar {
  margin-top: 16px;
  background: #f0f0f0;
  border-radius: 4px;
  height: 20px;
  position: relative;
  overflow: hidden;
}

.progress-fill {
  background: linear-gradient(90deg, #007bff, #0056b3);
  height: 100%;
  transition: width 0.3s ease;
}

.progress-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 12px;
  color: #333;
  font-weight: bold;
}

.error-message {
  margin-top: 16px;
  padding: 12px;
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
  border-radius: 4px;
}

.success-message {
  margin-top: 16px;
  padding: 12px;
  background: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
  border-radius: 4px;
}

.image-info {
  margin-top: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.image-info h4 {
  margin: 0 0 12px 0;
  color: #333;
}

.image-info p {
  margin: 4px 0;
  font-size: 14px;
  color: #666;
}

.image-info a {
  color: #007bff;
  text-decoration: none;
}

.image-info a:hover {
  text-decoration: underline;
}
</style> 